<template>
  <el-container class="template-layout">
    <!-- 顶部查询 -->
    <el-header v-if="showSearchHeader">
      <zz-Search
        :searchOptions="searchOptions"
        :loading="loading"
        @getSearchData="getSearchData"
        @resetFields="resetFields"
      />
    </el-header>

    <el-main>
      <!-- 工具栏与右侧操作：表格尺寸/显示查询/列设置 -->
      <zz-PageBar>
        <template #buttons>
          <el-button type="primary" @click="addItem">{{
            $t("common.add")
          }}</el-button>
          <el-button type="danger" @click="delItems" plain>{{
            $t("common.delete")
          }}</el-button>
        </template>
        <template #right>
          <el-dropdown @command="handleSizeChange">
            <el-button :icon="'Switch'" circle />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="mini">{{
                  $t("table.mini")
                }}</el-dropdown-item>
                <el-dropdown-item command="small">{{
                  $t("table.small")
                }}</el-dropdown-item>
                <el-dropdown-item command="medium">{{
                  $t("table.medium")
                }}</el-dropdown-item>
                <el-dropdown-item command="large">{{
                  $t("table.large")
                }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button
            :icon="'Search'"
            circle
            @click="showSearchHeader = !showSearchHeader"
          />
          <el-button
            :icon="'Operation'"
            circle
            @click="showColumnSetting = true"
          />
        </template>
      </zz-PageBar>

      <!-- 表格：列与字段暂留不写，后续补齐 -->
      <zz-Table
        ref="tableRef"
        :key="tableKey"
        :data="tableData"
        :size="tabelSize"
        :loading="loading"
        :page="tablePage"
        :hasPage="true"
        @pageChange="pageChange"
      >
        <vxe-column type="checkbox" fixed="left" width="40" />
        <vxe-column type="seq" fixed="left" width="50" />

        <!-- 动态列渲染：根据 tableColumns -->
        <template v-for="column in tableColumns" :key="column.field">
          <vxe-column
            v-if="column.visible"
            :field="column.field"
            :title="column.title"
            :fixed="column.fixed"
            :width="150"
          >
            <template #default="{ row }">
              <template v-if="column.field === 'userCode'">
                <a @click="editItem(row)">{{ row[column.field] }}</a>
              </template>
              <template v-else>
                {{ row[column.field] }}
              </template>
            </template>
          </vxe-column>
        </template>

        <!-- 操作列 -->
        <vxe-column :title="$t('common.operation')" :width="200" fixed="right">
          <template v-slot="{ row }">
            <zz-TableBtn
              type="text"
              :loading="btnLoading"
              @click="viewItem(row)"
              >{{ $t("common.view") }}</zz-TableBtn
            >
            <zz-TableBtn
              type="error"
              :loading="btnLoading"
              @click="delItem(row)"
              >{{ $t("common.delete") }}</zz-TableBtn
            >
          </template>
        </vxe-column>
      </zz-Table>
    </el-main>
  </el-container>

  <!-- 业务组件 -->
  <addAuthUser
    ref="addAuthUserRef"
    v-model="addAuthUserIsOpen"
    @query="query"
  ></addAuthUser>

  <!-- 列设置：使用本地存储，键名 auth-user_columns -->
  <zz-ColumnSetting
    v-model="showColumnSetting"
    :columns="tableColumns"
    :default-columns="defaultTableColumns"
    storage-key="auth-user_columns"
    list-id="auth-user-column-list"
    drawer-class="auth-user-column-setting-drawer"
    @confirm="handleColumnConfirm"
    @cancel="handleColumnCancel"
    @reset="handleColumnReset"
  />
</template>

<script setup>
import addAuthUser from "./components/addAuthUser.vue";
import { computed, getCurrentInstance, onMounted, ref } from "vue";
const { proxy } = getCurrentInstance();

// UI 状态
const showSearchHeader = ref(true);
const showColumnSetting = ref(false);
const loading = ref(false);
const btnLoading = ref(false);

// 初始化
const init = () => {
  // todo:
  loadColumnSettings();
};

// 查询模型与配置
const searchModel = ref({
  userCode: "",
  userName: "",
  sex: "",
  birthDayRange: [],
  role: "",
  telephone: "",
  createDateRange: [],
  updateDateRange: [],
});

const searchOptions = computed(() => ({
  model: searchModel,
  column: [
    {
      label: "用户编码",
      type: "inputText",
      field: "userCode",
    },
    {
      label: "用户名称",
      type: "inputText",
      field: "userName",
    },
    {
      label: "性别",
      type: "inputText",
      field: "sex",
    },
    {
      label: "出生日期",
      type: "datePicker",
      field: "birthDayRange",
      dateType: "daterange",
      span: 12,
    },
    {
      label: "角色名称",
      type: "inputText",
      field: "role",
    },
    {
      label: "手机号",
      type: "inputText",
      field: "telephone",
    },
    {
      label: "创建时间",
      type: "datePicker",
      field: "createDateRange",
      dateType: "datetimerange",
      span: 12,
    },
    {
      label: "更新时间",
      type: "datePicker",
      field: "updateDateRange",
      dateType: "datetimerange",
      span: 12,
    },
  ],
}));

// 查询事件
const getSearchData = (val) => {
  searchModel.value = val;
  query("search");
};
// 重置查询表单
const resetFields = () => {
  searchModel.value = {
    userCode: "",
    userName: "",
    sex: "",
    role: "",
    telephone: "",
  };
};

// 表格与分页
const tableData = ref([]);
const tablePage = ref({ pageNum: 1, pageSize: 15, total: 0 });
const tabelSize = ref("small");
const tableRef = ref(null);

// 处理表格大小变化
const handleSizeChange = (size) => {
  tabelSize.value = size;
};

// 列配置与本地存储键
const STORAGE_KEY = proxy.$CONS.STORAGE_KEY;
const tableKey = ref(0);

// 当前列配置与默认列
const tableColumns = ref([
  {
    field: "userCode",
    title: "用户编码",
    visible: true,
    fixed: "left",
  },
  {
    field: "userName",
    title: "用户名称",
    visible: true,
    fixed: null,
  },
  {
    field: "sex",
    title: "性别",
    visible: true,
    fixed: null,
  },
  {
    field: "birthDay",
    title: "出生日期",
    visible: true,
    fixed: null,
  },
  {
    field: "age",
    title: "年龄",
    visible: true,
    fixed: null,
  },
  {
    field: "telephone",
    title: "手机号",
    visible: true,
    fixed: null,
  },
  {
    field: "failureTime",
    title: "失效时间",
    visible: true,
    fixed: null,
  },
  {
    field: "createDate",
    title: "创建时间",
    visible: true,
    fixed: null,
  },
  {
    field: "updateDate",
    title: "更新时间",
    visible: true,
    fixed: null,
  },
]);
const defaultTableColumns = ref([
  {
    field: "userCode",
    title: "用户编码",
    visible: true,
    fixed: "left",
  },
  {
    field: "userName",
    title: "用户名称",
    visible: true,
    fixed: null,
  },
  {
    field: "sex",
    title: "性别",
    visible: true,
    fixed: null,
  },
  {
    field: "birthDay",
    title: "出生日期",
    visible: true,
    fixed: null,
  },
  {
    field: "age",
    title: "年龄",
    visible: true,
    fixed: null,
  },
  {
    field: "telephone",
    title: "手机号",
    visible: true,
    fixed: null,
  },
  {
    field: "failureTime",
    title: "失效时间",
    visible: true,
    fixed: null,
  },
  {
    field: "createDate",
    title: "创建时间",
    visible: true,
    fixed: null,
  },
  {
    field: "updateDate",
    title: "更新时间",
    visible: true,
    fixed: null,
  },
]);

// 处理列设置确认
const handleColumnConfirm = (columns) => {
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
  all["auth-user_columns"] = tableColumns.value;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  tableKey.value += 1;
};
// 处理列设置取消
const handleColumnCancel = () => {
  loadColumnSettings();
};
// 处理列设置重置
const handleColumnReset = (columns) => {
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
  all["auth-user_columns"] = tableColumns.value;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  tableKey.value += 1;
};

// 加载已保存列设置
const loadColumnSettings = () => {
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY))?.[
      "auth-user_columns"
    ];
    if (saved) tableColumns.value = saved;
    tableKey.value += 1;
  } catch (e) {
    console.error("加载列设置失败:", e);
  }
};

// 查询
const query = async (mode) => {
  loading.value = true;
  if (mode === "search") {
    searchModel.value.queryParam = {
      pageNum: 1,
      pageSize: 15,
      total: 0,
    };
  }
  // TODO: 接入测试管理查询接口，替换为真实 API
  let params = dealParams();
  let res = await proxy.$API.authUserManagement.authUser.queryWithPage.post(
    params
  );
  if (res.code === "01") {
    tableData.value = res.bizList;
    tablePage.value.total = res.total;
    tablePage.value.pageSize = res.pageSize;
  }
  loading.value = false;
};
// 处理查询参数
const dealParams = () => {
  let params = {
    ...searchModel.value,
  };

  // 其他的参数转化逻辑，如日期格式等
  return params;
};

// 业务操作占位
const addAuthUserRef = ref(null);
const addAuthUserIsOpen = ref(false);
const addItem = () => {
  addAuthUserIsOpen.value = true;
  addAuthUserRef.value.type = "add";
  addAuthUserRef.value.title = "新增用户";
};
const delItems = async () => {
  const rows = tableRef.value?.getCheckboxRecords?.() || [];
  if (rows.length === 0) return proxy.$message.warning("请选择要删除的数据");
  let ids = rows.map((e) => e.userId);
  proxy
    .$confirm(`确定要删除吗`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      let res = await proxy.$API.authUserManagement.authUser.deleteBatch.post(
        ids
      );
      if (res.code === "01") {
        query("search");
        proxy.$message.success("删除成功");
      } else {
        proxy.$message.error(res.msg || "删除失败");
      }
    })
    .catch(() => {
      proxy.$message.info("已取消删除");
    });
};
const delItem = async (row) => {
  let id = row.userId;
  proxy
    .$confirm(`确定要删除吗？`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      let res = await proxy.$API.authUserManagement.authUser.delete.get(id);
      if (res.code === "01") {
        query("search");
        proxy.$message.success("删除成功");
      } else {
        proxy.$message.error(res.msg || "删除失败");
      }
    })
    .catch(() => {
      proxy.$message.info("已取消删除");
    });
};
const viewItem = (row) => {
  addAuthUserIsOpen.value = true;
  addAuthUserRef.value.type = "view";
  addAuthUserRef.value.title = "查看用户";
  addAuthUserRef.value.model = { ...row };
};
const editItem = (row) => {
  addAuthUserIsOpen.value = true;
  addAuthUserRef.value.type = "edit";
  addAuthUserRef.value.title = "编辑用户";
  addAuthUserRef.value.model = { ...row };
};

// 翻页
const pageChange = (page) => {
  searchModel.value.queryParam.pageNum = page.currentPage;
  searchModel.value.queryParam.pageSize = page.pageSize;
  query();
};

onMounted(() => {
  init();
  query("search");
});
</script>

<style lang="less" scoped></style>
